package com.sywb.chuangyebao.view;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.contract.PublishVideoEditContract;
import com.sywb.chuangyebao.utils.Utils;
import com.sywb.chuangyebao.view.dialog.AlertDialog;

import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.StatusBarUtils;
import org.bining.footstone.utils.ToastUtils;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTouch;

/**
 * 发布视频-视频编辑
 * Created by duxl on 2018/5/24.
 */

public class PublishVideoEditActivity extends ActionbarActivity<PublishVideoEditContract.Presenter> implements PublishVideoEditContract.View {

    @BindView(R.id.surfaceView_fragment_publish_video_edit)
    SurfaceView mSurfaceView;

    @BindView(R.id.pbProgress_fragment_publish_video_edit)
    ProgressBar mProgressBar;

    @BindView(R.id.ivPlay_fragment_publish_video_edit)
    ImageView mIvPlay;

    @BindView(R.id.etText_fragment_publish_video_edit)
    EditText mEtText;

    @BindView(R.id.tvTextCount_fragment_publish_video_edit)
    TextView mTvTextCount;

    @BindView(R.id.tvCopyToDCIM_fragment_publish_video_edit)
    TextView mTvCopyToDCIM;
    @BindView(R.id.tvPublish_fragment_publish_video_edit)
    Button publishVideo;
    private String mVideoSource; // 视频url地址
    private int mSourceType; // 视频来源：0相册、1拍摄、2我的视频
    private int mVideoDuration; // 视频播放时间(秒)，mSourceType=2时，可以传入0
    private String mVideoId; // 视频id，mSourceType=2时，必须传入
    private String mVideoTitle; // 视频标题，mSourceType=2时，必须传入

    private Handler mHander = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            if (msg.what == 0) {
                if (mIvPlay != null) {
                    mIvPlay.setVisibility(View.GONE);
                }
            }
        }
    };

    @Override
    public int getLayoutId(Bundle bundle) {
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
        return R.layout.activity_publish_video_edit;
    }

    @Override
    public boolean useLightMode() {
        return false;
    }

    @Override
    public void initPresenter() {
        mPresenter.initPresenter(this);
    }

    @Override
    public void initView(Bundle bundle) {
        super.initView(bundle);

        if (bundle == null) {
            bundle = getIntent().getExtras() == null ? new Bundle() : getIntent().getExtras();
        }

        // StatusBarUtils.setStatusBarMode(mActivity, false);
        StatusBarUtils.setColorByOpaque(mActivity, ContextCompat.getColor(mContext, R.color.colorBlack));

        setTitle("发布");
        setBackgroundByRes(R.color.colorBlack);
        setBackRes(R.drawable.ic_back_white);
        setTitleColor(ContextCompat.getColor(mContext, R.color.colorLight));
        setsBottomLineColor("#2C2C2C");

        mVideoSource = bundle.getString("p0"); // 【必须】视频url地址
        mSourceType = bundle.getInt("p1"); // 【必须】视频来源：0相册、1拍摄、2我的视频
        mVideoDuration = bundle.getInt("p2"); // 【可选】视频播放时间(秒)，mSourceType=2时，可以传入0
        mVideoId = bundle.getString("p3"); // 【可选】视频id，mSourceType=2时，必须传入
        mVideoTitle = bundle.getString("p4"); // 【可选】视频标题，mSourceType=2时，必须传入
        //mVideoSource = "http://1253842527.vod2.myqcloud.com/3759e4e6vodgzp1253842527/745ab8f97447398155569085068/6js82DHU2NAA.mp4";

        Logger.i("视频文件：" + mVideoSource);

        mIvPlay.setVisibility(View.GONE);
        mSurfaceView.setEnabled(false);
        mSurfaceView.setKeepScreenOn(true);
        // mSurfaceView.setZOrderOnTop(true);
        mEtText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mTvTextCount.setText(String.valueOf(getResources().getInteger(R.integer.video_text_count) - s.length()));
            }
        });

        if (mSourceType != 1) { // 录制视频的时候，才有保存到相册功能
            mTvCopyToDCIM.setVisibility(View.GONE);
        }

        if(mSourceType == 2) {
            mEtText.setText(mVideoTitle);
            mEtText.setSelection(mEtText.length());
            publishVideo.setClickable(false);
            publishVideo.setBackgroundResource(R.drawable.round3_pie_gray_light);
        }else{
            publishVideo.setClickable(true);
            publishVideo.setBackgroundResource(R.drawable.round3_pie_theme);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPresenter.pause();
    }

    @OnClick(R.id.tvPublish_fragment_publish_video_edit)
    public void onClickPublish(View v) { // 发布
        if (!isCanClick(v)) return;
        if (mPresenter.isPlaying()) {
            mPresenter.pause();
            mIvPlay.setVisibility(View.VISIBLE);
        }

        if(TextUtils.isEmpty(getVideoDesc())) {
            showMessage(getString(R.string.video_text_empty));
            mEtText.requestFocus();
        } else {
            mPresenter.publish();
        }
    }

    @OnClick(R.id.ivPlay_fragment_publish_video_edit)
    public void onClickPlay(View v) { // 播放、暂停
        if (!isCanClick(v)) return;
        mHander.removeMessages(0);
        if (mPresenter.isPlaying()) {
            mPresenter.pause();
            mIvPlay.setImageResource(R.drawable.publish_v_edit_play);
        } else {
            mPresenter.play();
            v.setVisibility(View.GONE);
            mIvPlay.setImageResource(R.drawable.publish_v_edit_stop);
        }
    }

    @OnClick(R.id.tvCopyToDCIM_fragment_publish_video_edit)
    public void onClickCopyToDCIM(View v) { // 保存到相册
        v.setSelected(!v.isSelected());
        if (v.isSelected()) { // 复制文件到相册
            Utils.copyFileToDCIM(this, new File(mVideoSource));
            Logger.i("复制文件: " + mVideoSource);

        } else { // 删除相册对应的文件
            Utils.delFileFromDCIM(new File(mVideoSource).getName());
            Logger.i("删除文件: " + mVideoSource);
        }
    }

    @OnTouch(R.id.surfaceView_fragment_publish_video_edit)
    public boolean onTouchSurfaceView(SurfaceView v, MotionEvent event) {
        mIvPlay.setVisibility(View.VISIBLE);
        mHander.removeMessages(0);

        if (event.getAction() == MotionEvent.ACTION_UP
                || event.getAction() == MotionEvent.ACTION_CANCEL) {
            if(mPresenter.isPlaying()) {
                mHander.sendEmptyMessageDelayed(0, 3000);
            }
        }
        return false;
    }

    @Override
    public void showMessage(String message) {
        ToastUtils.show(mContext, message);
    }

    @Override
    public SurfaceView getSurfaceView() {
        return mSurfaceView;
    }

    @Override
    public String getVideoSource() {
        return mVideoSource;
    }

    @Override
    public String getVideoDesc() {
        return mEtText.getText().toString().trim();
    }

    @Override
    public ProgressBar getProgressBar() {
        return mProgressBar;
    }

    @Override
    public int getVideoDuration() {
        return mVideoDuration;
    }

    @Override
    public int getSourceType() {
        return mSourceType;
    }

    @Override
    public String getVideoId() {
        return mVideoId;
    }

    @Override
    public void onPlayCompleted() {
        mIvPlay.setVisibility(View.VISIBLE);
        mIvPlay.setImageResource(R.drawable.publish_v_edit_play);
    }

    @Override
    public void showPublishSuccessDialog() {
        RxBus.get().post(Constants.POST_VIDEO_SAVE, "");
        String btn = getString(R.string.btn_confirm);
        String msg = getString(R.string.publish_success);
        AlertDialog dialog = AlertDialog.newInstance(null, msg, btn,null, true);
        dialog.setClickListener(new AlertDialog.OnClickListener() {
            @Override
            public void onClick(int position) {
              exit(false);
            }
        });
        dialog.show(getMyFragmentManager(), "showPublishSuccessDialog");
    }
}
